<script setup lang="ts">
import { ElMessage, type FormInstance, type FormRules } from "element-plus";
import { Plus,Delete } from "@element-plus/icons-vue"
import { ref, reactive, defineProps, onMounted, watch } from "vue";
import { post, get } from "@/libs/request";
import uploadImageCase from '@/components/uploadImageCase.vue'
import uploadImageListCase from '@/components/uploadImageListCase.vue'
import EditorCase from '@/components/EditorCase.vue'
import { calcDescartes } from "@/libs/util"
const props = defineProps(["close", "params"]);
const ruleForm = reactive({
  catId:undefined,
  goodsName: undefined,
  goodsKeyword: undefined,
  goodsCover:undefined,
  goodsGallery:[],
  goodsDesc:undefined,
  goodsContent:undefined,
  unitName:undefined,
  specType:false,
  isShow: false,
  attr:[],
  spec:<any>[],
});
const rules = reactive<FormRules>({
  catId: [{ required: true, message: "请选择商品分类", trigger: "blur" }],
  goodsName: [{ required: true, message: "请输入商品名称", trigger: "blur" }],
  goodsCover: [{ required: true, message: "需要上传商品封面图", trigger: "blur" }],
  unitName: [{ required: true, message: "请输入商品单位", trigger: "blur" }],
});
const catId = ref();
//分类列表
const goodsCategory = ref([]);
//表单提交
const ruleFormRef = ref<FormInstance>();
// 规格列表
const spec = ref([{
    keyName:ruleForm.goodsName,
    cover:"",
    content:"",
    oldPrice:0.00,
    price:0.00,
    storeCount:0,
    barCode:"",
}]);
/**
 * 添加属性
 */
const addAttr = ()=>{
  ruleForm.attr.push({  
    attrName:"",
    setImage:false,
    attrValues:[
        {
          attrValueName:"",
          attrValueImage:"",
        }
      ]
  });
}
/**
 * 添加属性值
 */
const addAttrValue = (v:any)=>{
  v.attrValues.push({
    attrValueName:"",
    attrValueImage:"",
  })
}
/**
 * 删除属性
 * @param i 
 */
const deleteAttr = (i:number)=>{
  ruleForm.attr.splice(i,1)
}
/**
 * 删除属性值
 * @param i 
 */
const deleteAttrValue = (i:number,ii:number)=>{
  ruleForm.attr[i].attrValues?.splice(ii,1)
}
/**
 * 删除规格
 */
const deleteSpec = (i:number)=>{
  if(spec.value.length==1){
    ElMessage.error("最少保留一个规格");
    return;
  }
  spec.value.splice(i,1)
}
/**
 * 获取商品分类
 */
const getGoodsCategory = async()=>{
  const res = await get("goodsCategory/getTree");
  if (res.errCode == 0) {
    goodsCategory.value = res.data;
  }
}
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
    ruleForm.catId = Number(catId.value[catId.value.length-1]);
  await formEl.validate((valid) => {
    if (valid) {
      ruleForm.spec = spec;
      post("goods/add", {
        ...ruleForm,
      }).then((res) => {
        if (res.errCode == 0) {
          ElMessage.success(res.errMsg);
          props.close();
        }
      });
    }
  });
};
watch(()=>[ruleForm.specType,ruleForm.goodsName,ruleForm.attr],()=>{
  let copySpec = JSON.parse(JSON.stringify(spec.value));
  spec.value = [];
  if(!ruleForm.specType){
    spec.value.push({
      keyName:ruleForm.goodsName,
      cover:"",
      content:"",
      oldPrice:0.00,
      price:0.00,
      storeCount:0,
      barCode:"",
    });
  }else{
    let arr = [];
    ruleForm.attr.forEach((v)=>{
      if(!v.attrValues.length) return;
      let item = []
      v.attrValues.forEach((vv)=>{
        if(!vv.attrValueName.length) return;
        item.push(`${v.attrName}:${vv.attrValueName}`);
      })
      arr.push(item)
    })
    calcDescartes(arr).forEach((keyName)=>{
      if(!keyName || !keyName.length) return;
      if(arr.length==1){
        keyName.forEach((v) => {
          let tag = copySpec.findIndex((vv: any) => {
            return vv.keyName == v;
          });
          if (tag == -1) {
            spec.value.push({
              keyName: v,
              cover: "",
              content: "",
              oldPrice: 0.00,
              price: 0.00,
              storeCount: 0,
              barCode: "",
            });
          }else{
            spec.value.push(copySpec[tag])         
          }
        })
      }else{
        let tag = copySpec.findIndex((vv: any) => {
          return vv.keyName == JSON.stringify(Object.assign(keyName));
        });
        if (tag == -1) {
          spec.value.push({
            keyName: JSON.stringify(Object.assign(keyName)),
            cover: "",
            content: "",
            oldPrice: 0.00,
            price: 0.00,
            storeCount: 0,
            barCode: "",
          });
        } else {
          spec.value.push(copySpec[tag])
        }
      }
    })
  }
},{deep:true})
onMounted(() => {
  getGoodsCategory()
})
</script>
<template>
  <div class="page">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item @click="props.close()">商品列表</el-breadcrumb-item>
      <el-breadcrumb-item>新增商品</el-breadcrumb-item>
    </el-breadcrumb>
    <div class="main">
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="100"
      >
        <el-form-item label="商品分类" prop="catId">
          <el-cascader :options="goodsCategory" v-model="catId" :props="{
            label:'catName',
            value:'catId'
          }"/>
        </el-form-item>
        <el-form-item label="商品名称" prop="goodsName">
          <el-input v-model="ruleForm.goodsName" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="商品关键字" prop="goodsKeyword">
          <el-input v-model="ruleForm.goodsKeyword" placeholder="请输入商品关键字" />
        </el-form-item>
        <el-form-item label="商品单位" prop="unitName">
          <el-input v-model="ruleForm.unitName" placeholder="请输入商品单位" />
        </el-form-item>
        <el-form-item label="封面图" prop="goodsCover">
            <upload-image-case v-model="ruleForm.goodsCover" action="common/uploadPic" name="img"></upload-image-case>
        </el-form-item>
        <el-form-item label="图片画册" prop="goodsGallery">
            <upload-image-list-case v-model="ruleForm.goodsGallery" action="common/uploadPic" name="img" list-type="picture-card"></upload-image-list-case>
        </el-form-item>
        <el-form-item label="商品简介" prop="goodsDesc">
          <el-input v-model="ruleForm.goodsDesc" :rows="3" type="textarea" placeholder="请输入商品描述" :maxlength="50" show-word-limit/>
        </el-form-item>
        <el-form-item label="详情" prop="goodsContent">
          <editor-case v-model="ruleForm.goodsContent"></editor-case>
        </el-form-item>
        <el-form-item label="商品规格" prop="specType">
          <el-radio-group v-model="ruleForm.specType" class="ml-4">
            <el-radio :label="false" size="large" checked>单规格</el-radio>
            <el-radio :label="true" size="large">多规格</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="ruleForm.specType">
          <el-form
            :model="ruleForm"
            :rules="rules"
            label-position="top"
            style="width:100%;"
          >
            <el-button type="primary" style="margin-bottom: 18px;" @click="addAttr()">
              <el-icon><Plus /></el-icon> 
              <span class="ml-5px">添加属性项</span>
            </el-button>
            <el-card shadow="hover" v-for="(v,i) in ruleForm.attr" :key="i" style="margin: 5px 0px;">
              <el-icon class="float-right" @click="deleteAttr(i)"><Delete color="#f56c6c"/></el-icon>
              <el-form-item label="规格项" style="margin: 0 5px;">
                <div class="flex">
                  <el-input placeholder="请输入规格项名称" v-model="v.attrName"></el-input>
                  <el-switch style="margin-left:5px" v-model="v.setImage"/><span style="width:150px">&nbsp;添加规格图片</span>
                </div>
              </el-form-item>
              <el-form-item label="规格值"  style="margin-top: 18px;">
                <el-card shadow="hover" style="margin:5px;" v-for="(vv,ii) in v.attrValues" :key="`${i}-${ii}`">
                  <div class="flex items-center">
                    <div>
                      <el-input placeholder="请输入规格值" v-model="vv.attrValueName"></el-input>
                      <upload-image-case v-model="vv.attrValueImage" action="common/uploadPic" name="img" style="width:150px;height:150px;margin: 5px auto;" v-if="v.setImage"></upload-image-case>
                    </div>
                    <el-icon style="margin-left: 5px;" @click="deleteAttrValue(i,ii)"><Delete color="#f56c6c"/></el-icon>
                  </div>
                </el-card>
                <el-button style="margin-left: 5px;" @click="addAttrValue(v)">
                  <el-icon><Plus /></el-icon> 
                  <span class="ml-5px">添加属性值</span>
                </el-button>
              </el-form-item>
            </el-card>
          </el-form>
        </el-form-item>
        <el-form-item >
          <el-table :data="spec" style="width: 100%">
            <el-table-column prop="keyName" label="规格组合" align="center" width="200"/>
            <el-table-column label="规格图片" align="center">
              <template #default="scope">
                <upload-image-case v-model="scope.row.cover" action="common/uploadPic" name="img"></upload-image-case>
              </template>
            </el-table-column>
            <el-table-column label="原价" align="center">
              <template #default="scope">
                <el-input-number v-model="scope.row.oldPrice" :precision="2" :controls="false"/>
              </template>
            </el-table-column>
            <el-table-column label="售价" align="center">
              <template #default="scope">
                <el-input-number v-model="scope.row.price" :precision="2" :controls="false"/>
              </template>
            </el-table-column>
            <el-table-column label="库存" align="center">
              <template #default="scope">
                <el-input-number v-model="scope.row.storeCount" :step="1" step-strictly :controls="false"/>
              </template>
            </el-table-column>
            <el-table-column label="条形码" align="center">
              <template #default="scope">
                <el-input v-model="scope.row.barCode" placeholder="请输入商品条形码" />
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" fixed="right">
              <template #default="scope">
                <el-button type="danger" @click="deleteSpec(scope.$indexx)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item label="状态" prop="isShow">
          <el-switch
            v-model="ruleForm.isShow"
          />
        </el-form-item>
        <el-form-item class="active">
          <el-button type="primary" @click="submitForm(ruleFormRef)">
            提交
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>